﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WSS.Web.Resource
{
    /// <summary>
    /// UploadHandle_Import 的摘要说明
    /// </summary>
    public class UploadHandle_Import : IHttpHandler
    {
        private string UPLOADIFY_SAVETO { get; set; }

        private string _get_upload_saveto()
        {
            string upload_saveto;

            var appsettings = System.Configuration.ConfigurationManager.AppSettings.AllKeys;

            if (appsettings.Contains("Uploadify_SaveTo"))
            {
                UPLOADIFY_SAVETO = System.Configuration.ConfigurationManager.AppSettings["Uploadify_SaveTo"];

                upload_saveto = UPLOADIFY_SAVETO;

                upload_saveto = System.Web.HttpContext.Current.Server.MapPath(upload_saveto);

                if (!System.IO.Directory.Exists(upload_saveto))
                {
                    System.IO.Directory.CreateDirectory(upload_saveto);
                }
            }
            else
            {
                throw new Exception("web.config 文件 appsetting 节点未配置 Uploadify_SaveTo ");
            }

            return upload_saveto;
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            HttpPostedFile file = context.Request.Files["Filedata"];
            string upload_path = _get_upload_saveto() + "/" + context.Request["folder"];

            if (file != null)
            {

                if (!System.IO.Directory.Exists(upload_path))
                {
                    System.IO.Directory.CreateDirectory(upload_path);
                }

                string filename = System.IO.Path.GetFileName(file.FileName);

                string physical_path = upload_path + "/" + filename;
                file.SaveAs(physical_path);

                context.Response.Write("1");
            }
            else
            {
                context.Response.Write("0");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}